package com.zt.csp.shorturl.task;

import com.ecfront.dew.common.$;
import com.zt.csp.shorturl.constents.RedisKey;
import com.zt.csp.shorturl.entity.ShortUrl;
import com.zt.csp.shorturl.mapper.ShortUrlMapper;
import com.zt.csp.shorturl.utils.ConvertRadix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务，清理缓存，计算当日浏览量
 * Created by zt on 2018/4/18 0018
 */
@Component
public class RedisTask {
    private static final Logger logger = LoggerFactory.getLogger(RedisTask.class);

    @Autowired
    private ShortUrlMapper shortUrlMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 每天0点清除当天的防重复缓存
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void cleanCache() {
        logger.info("删除当天的防重复信息...");
        redisTemplate.boundValueOps(RedisKey.LONG_SHORT_HASH);
        redisTemplate.delete(RedisKey.LONG_SHORT_HASH);
        logger.info("删除成功");
    }

    /**
     * 每天0点统计每天的访问量
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void countView() {
        Map<String, String> map = redisTemplate.opsForHash().entries(RedisKey.SHORT_COUNT)
                .entrySet().stream().collect(
                        Collectors.toMap(i -> (String) (i.getKey()), i -> (String) (i.getValue())));


        logger.info("开始记录浏览量，当天的浏览量数据为: [{}]", $.json.toJsonString(map));
        map.forEach((id, view) -> {
            ShortUrl shortUrl = shortUrlMapper.selectById(Long.valueOf(id));
            Integer viewSaved = shortUrl.getView();
            viewSaved += Integer.valueOf(view);
            shortUrl.setView(viewSaved);
            logger.info("短链接[{}]的浏览量目前为：{}", ConvertRadix._10_to_N(Long.valueOf(id), 62), viewSaved);
            shortUrlMapper.updateById(shortUrl);
        });
        logger.info("删除当天的浏览量信息...");
        redisTemplate.delete(RedisKey.SHORT_COUNT);
        logger.info("删除成功");
    }
}
